package backend;

import backend.Instruction.RISCVinst;
import backend.component.*;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;

public class RISCVBuilder {
    private static final String SECTION_TEXT_STARTUP = ".section\t.text.startup";
    private static final String SECTION_TEXT = ".section\t.text";
    private static final String ALIGN = ".align\t1";
    private static final String GLOBAL = ".globl\t"; //global
    private static final String FUNCTION_LABEL = "\n%s:\n";

    private BufferedWriter bufferedWriter;

    public RISCVBuilder(String filename) {
        try {
            bufferedWriter = new BufferedWriter(new FileWriter(filename));
        } catch (IOException e) {
            System.err.println("Error opening file: " + e.getMessage());
        }
    }

    private void writeMainFunctionSection(BufferedWriter bufferedWriter) throws IOException {
        bufferedWriter.write(SECTION_TEXT_STARTUP);
        bufferedWriter.newLine();
        bufferedWriter.write(ALIGN);
        bufferedWriter.newLine();
        bufferedWriter.write(GLOBAL + "main");
    }

    private void writeRegularFunctionSection(BufferedWriter bufferedWriter) throws IOException {
        bufferedWriter.write(SECTION_TEXT);
        bufferedWriter.newLine();
        bufferedWriter.write(ALIGN);
        bufferedWriter.newLine();
    }
    public void dumpRISC_V(RISCVmodule riscvModule) {
        try {
            //处理全局变量
            for (RISCVglobalvar var : riscvModule.getGlobalVariables()) {
                bufferedWriter.write(var.toString() + "\n");
            }
            //处理函数块
            for (RISCVfunction func : riscvModule.getFunctions()) {
                //区分main 函数 和成员函数
                if (func.getName().equals("main")) {
                    writeMainFunctionSection(bufferedWriter);
                } else {
                    writeRegularFunctionSection(bufferedWriter);
                }
                //开始写function
                bufferedWriter.write(String.format(FUNCTION_LABEL, func.getName()));
                //遍历 函数里面的基本快 写入基本块
                for (RISCVblock block : func.getBlocks()) {
                    bufferedWriter.write(block.getName() + ":\n");
                    //遍历基本块的 指令 ，写入指令
                    for (RISCVinst instr : block.getInstructionlist()) {
                        bufferedWriter.write("\t" + instr.toString());
                    }
                }
                bufferedWriter.write("\n");
            }
        } catch (IOException e) {
            System.err.println("Error processing module: " + e.getMessage());
        } finally {
            try {
                bufferedWriter.close();
            } catch (IOException e) {
                System.err.println("Error closing file: " + e.getMessage());
            }
        }
    }

}
